#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "strlist.h"

str_link_t create_strlink(){
    str_link_t link;
    link = (str_link_t)malloc( sizeof(struct str_link) );
    if( link == NULL){
        perror("create str link failure ");
        exit(-1);
    }
    link->len = 0;
    link->head= link->tail = NULL;
    return link;
}

void destroy_strlink(str_link_t link){
    if(link){
        while(link->head != NULL){
            link_entry_t next = link->head;
            link->head = next->next_ptr;
            next->next_ptr = NULL;
            free(next);
        }
        link->len = 0;
        link->head = link->tail = NULL;
        free(link);
    }
}

void insert_strlink(link_entry_t str, str_link_t link){
    str->next_ptr = NULL;
    if(link){
        if(link->head != NULL){
            link->tail->next_ptr = str;
            link->tail = str;
        }else{
            link->head = link->tail = str;
        }
        link->len += 1;
    }
}

/* 删除指定内容的节点 */
void remove_strlink(const char *str, str_link_t link){    
    link_entry_t node = link->head;      //用于索引指针
    link_entry_t tmp;             //记录要删除的上一个节点    
    if(link){       
        if(strcmp(str, node->str) == 0){               
            link->head = node->next_ptr; 
            node->next_ptr = NULL;
            free(node);
            node = link->head;
            //printf("head->str: %s \n", link->head->str);
            //printf("tail->str: %s \n", link->tail->str);                                
            link->len -= 1;
        }
        

        while(node != NULL){            
            tmp = node;
            node = node->next_ptr;
            if(node == NULL){ //遍历完就退出循环                
                link->tail = tmp; //更新尾结点
                break;
            }
            if( strcmp(node->str, str) == 0 ){
                tmp->next_ptr = node->next_ptr;                
                node->next_ptr = NULL;
                free(node);
                node = tmp;                                
                link->len -= 1;                 
            }
        }
    }    
}

int find_strlink(const char *str, str_link_t link){    
    int count = 0;
    if( (strlen(str) > 0) &&  link ){
        link_entry_t node = link->head;
        while(node != NULL){
            if( strcmp(node->str, str) == 0 ){
                count++;
            }
            node = node->next_ptr;
        }
        free(node);
    }
    return count;
}